package com.datasecops.scannerservices.service;

import com.datasecops.scannerservices.config.ConfigFilePath;
import com.datasecops.scannerservices.enumerate.EngineStatus;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 扫描引擎服务调用相关
 * @author: SunLingzhi
 * @time: 2022/8/29 11:21
 */
@Service
@Slf4j
public class ScannerEngineServer {
    //private static final Logger logger = LogManager.getLogger(ScannerEngineServer.class);

    private final static Logger logger = LoggerFactory.getLogger(ScannerEngineServer.class);
    private int i = 0;

/*
    *//**
     * 调用ScannerAgent.exe
     *
     * @param
     * @param xmlPath
     * @return
     * @Description
     * @author SunLingzhi
     * @time 2022/8/16 16:22
     *//*
    public void callScannerEngine(String jobId, String model, String engineStatus, String xmlPath) {
        log.info("start call method callScannerEngine");

        //等待执行完成
        Process exec;
        try {
            File file = new File(ConfigFilePath.getScannerEngineExeFile());
            String absolutePath = file.getCanonicalPath();
            //引擎地址，扫描任务Id，模式，引擎状态，配置文件地址
            String[] ex;
            if (null != xmlPath){
                ex = new String[]{absolutePath, jobId, model, engineStatus, xmlPath};
            }else{
                ex = new String[]{absolutePath, jobId, model, engineStatus};
            }

            exec = Runtime.getRuntime().exec(ex);
            exec.waitFor();
        } catch (Exception e) {
            log.error("Failed Method startScanning error:" + e.getMessage());
        }
    }*/




     /**
      *调用ScannerAgent.exe（新）
      * @Description
      * @author GeXiaoLong
      * @time 2023/3/8 10:05
      * @param
      * @return
      */
    public void callScannerEngine(String jobId, String model, String engineStatus, String xmlPath) {
        log.info("start call method callScannerEngine");
        try {
            File file = new File(ConfigFilePath.getScannerEngineExeFile());
            String absolutePath = file.getCanonicalPath();
            logger.error("file的值是:"+file);
            logger.error("absolutePath的值是:"+absolutePath);
            //引擎地址，扫描任务Id，模式，引擎状态，配置文件地址
            // 命令语句
  /*          String[] command = new String[]{"./ScannerEngine", "--taskguid", "[ACAC592D-C8BD-4396-A09E-10882062C53C]", "--mode", "scanproxy", "--cmd", "data", "--config", "/var/n_dlp/bin/temp.xml"};*/
            String[] command = new String[0];
            if (EngineStatus.START.getValue().equalsIgnoreCase(engineStatus)){
                command = new String[]{"./ScannerEngine", "--taskguid", "[" + jobId + "]", "--mode", model, "--cmd", engineStatus};
                logger.error("扫描引擎已经接受到了任务,扫描任务ID为: "+jobId);
            }else if(EngineStatus.DATA.getValue().equalsIgnoreCase(engineStatus)){
                 command = new String[]{"./ScannerEngine", "--taskguid", "[" + jobId + "]", "--mode", model, "--cmd", engineStatus, "--config", xmlPath};
                logger.error("扫描引擎已经开始执行任务了,详细任务的执行路径为: "+xmlPath);
            }else if(EngineStatus.STOP.getValue().equalsIgnoreCase(engineStatus)){
                command = new String[]{"./ScannerEngine", "--taskguid", "[" + jobId + "]", "--mode", model, "--cmd", engineStatus};
                logger.error("扫描引擎已经发布了停止任务指令");
            }
            // 执行命令行命令
            //Process process = Runtime.getRuntime().exec(command, null, new File("/root/opt"));
            Process process = Runtime.getRuntime().exec(command, null, new File(absolutePath));
            i++;
            process.waitFor();
            System.out.println("数据库扫描执行了"+i+"次");
        } catch (Exception e) {
            logger.error("扫描引擎在执行是发生了错误,错误信息为:"+e.getMessage());
            log.error("Failed Method startScanning error:" + e.getMessage());
        }
        
        
        
    }
    //原版的命令行执行代码,仅供参考
    public  String mains() throws IOException {
        // 执行命令行命令
        String[] command = new String[]{"./ScannerEngine", "--taskguid", "[ACAC592D-C8BD-4396-A09E-10882062C53C]", "--mode", "scanproxy", "--cmd", "data", "--config", "/var/n_dlp/bin/temp.xml"};
        Process process = Runtime.getRuntime().exec(command, null, new File("/root/opt"));

        // 读取命令行输出
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line).append("\n");
        }

        // 等待命令行命令执行完成
        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new RuntimeException("Command execution failed with exit code " + exitCode);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Command execution interrupted", e);
        }

        return output.toString();
    }

    public static void main(String[] args) {
        ScannerEngineServer scannerEngineServer = new ScannerEngineServer();
        //>>>>>>>>>>1、调用扫描引擎--执行开始命令 ScannerEngine.exe
        scannerEngineServer.callScannerEngine("69D9AA90-18AA-0CDD-E3E9-87416E0FA15A", "scanproxy", EngineStatus.START.getValue(), null);
    }
}
